/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package meteocal.boundary;

import java.io.Serializable;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import meteocal.entityManager.UserManager;
import meteocal.utility.PasswordEncrypter;

/**
 *
 * @author andrea
 */
@Named(value = "loginBean")
@RequestScoped
public class LoginBean implements Serializable{
    
    private String email;
    private String password;
    
    @Inject
    private UserManager um;
    
    public LoginBean() {
    }
    
    public String getEmail() {
        return this.email;
    }
    
    public void setEmail(String email) {
        this.email = email;
    }
    
    public String getPassword() {
        return this.password;
    }
    
    public void setPassword(String password) {
        this.password = password;
    }
    
    public String login() {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        try {
            request.login(this.email, this.password);
            return "/user/home?faces-redirect=true";
        } catch (ServletException e) {
            if(this.um.getLoggedUser() != null){
                if(this.email.equals(um.getLoggedUser().getEmail()) && PasswordEncrypter.encryptPassword(this.password).equals(um.getLoggedUser().getPassword())){
                    return "/user/home?faces-redirect=true";
                
            }else{
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"There's another logged User","Login Failed"));
                return null;
                }
            }
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Login Failed","Login Failed"));
            return null;
        }
            
        
        }
    public String logout() {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        request.getSession().invalidate();
        return "/index?faces-redirect=true";
    }
    
}
